package utils

import (
	"github.com/gitstliu/go-redis-cluster"
	"github.com/spf13/viper"

	"errors"
	"time"
)

type RedisClusterHandler struct{}

func (h *RedisClusterHandler) From() string {
	return "redisCluster"
}

func (h *RedisClusterHandler) WriteDocuments(key string, value interface{}) error {

	cluster := GetRedisCluster()

	exit := false
	exit, _ = redis.Bool(cluster.Do("EXISTS", key))
	//fmt.Println("exit: ", exit)

	if !exit {

		inf, err := cluster.Do("set", key, value)
		if err != nil {
			return err
		}
		ins := inf.(string)
		if ins != "OK" {
			return errors.New("写入redis集群失败")
		}
		return nil
	}
	return errors.New("用户已注册")

}

func (h *RedisClusterHandler) ReadDocumets(key string) (value interface{}, err error) {

	cluster := GetRedisCluster()
	//defer cluster.Close()

	value, _ = redis.Bytes(cluster.Do("GET", key))

	if value != nil {
		return

	}
	err = errors.New("key not found")
	return
}

func (h *RedisClusterHandler) UpdateDocuments(key string, value interface{}) error {

	cluster := GetRedisCluster()
	//defer cluster.Close()

	inf, err := cluster.Do("SET", key, value)
	if err != nil {
		return err
	}
	ins := inf.(string)
	if ins != "OK" {
		return errors.New("用户信息更新失败")
	}

	return nil
}

func (h *RedisClusterHandler) DeleteDocuments(id string) error {
	cluster := GetRedisCluster()
	_, err := cluster.Do("del", id)
	return err
}

var RedisCluster *redis.Cluster

func GetRedisCluster() *redis.Cluster {
	return RedisCluster
}

func ClusterClient() (*redis.Cluster, error) {
	var err error
	node := viper.GetStringSlice("redisCluster.node")

	pwd := viper.GetString("redisCluster.pwd")

	RedisCluster, err = redis.NewCluster(
		&redis.Options{
			StartNodes:   node,
			ConnTimeout:  50 * time.Millisecond,
			ReadTimeout:  50 * time.Millisecond,
			WriteTimeout: 50 * time.Millisecond,
			KeepAlive:    16,
			AliveTime:    60 * time.Second,
		})
	if err != nil {
		return nil, err
	}
	_, err = RedisCluster.Do("AUTH", pwd)
	if err != nil {
		return nil, err
	}
	return RedisCluster, nil
}
